package com.tudulist.security;

import java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;
import javax.persistence.NoResultException;

import org.joda.time.DateTime;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tudulist.bo.UserManager;
import com.tudulist.model.Role;
import com.tudulist.model.User;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Inject
	UserManager userManager;

	@Transactional
	public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {

		login = login.toLowerCase();
		User user = null;
		try {
			user = userManager.findUser(login);
		} catch (AuthenticationException ae) {
			throw new UsernameNotFoundException("User '" + login + "' could not be found.");
		} catch (NoResultException ne) {
			throw new UsernameNotFoundException("User '" + login + "' could not be found.");
		}

		user.setLastAccessDate(new DateTime());
		userManager.updateUser(user);

		Set<Role> roles = new HashSet<Role>();
		if (user.getRoles() != null) {
			roles.addAll(user.getRoles());
		}
		Set<GrantedAuthority> arraysAuths = new HashSet<GrantedAuthority>();
		for (Role role : roles) {
			arraysAuths.add(new SimpleGrantedAuthority(role.getRole().label));
		}

		return new org.springframework.security.core.userdetails.User(login, user.getPassword(), user.isEnabled(), true, true, true, arraysAuths);
	}
}
